﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using HuiZe.education.Model;

namespace HuiZe.education.View
{
    /// <summary>
    /// PART_Media_Host.xaml 的交互逻辑
    /// </summary>
    public partial class PART_Media_Host : UserControl
    {
        public bool IsAutoPlay { get; set; }

        public PART_Media_Host()
        {
            InitializeComponent();
            Reset();
        }
        
        public void SetData(respResourceChildModel_Ethan _data, Action<bool> _callback_fullscreen = null)
        {
            _fullscreen_callback = _callback_fullscreen;

            Reset();
            if (_data == null)
            {
                return;
            }

            _media_type = GetType(_data.file);
            if (_media_type < 0) return;

            string _root_res_id = BuildRoot(_data.id);
            switch (_media_type)
            {
                case 0:
                    SetData_Radio(_root_res_id, _data.file, _data.lyric_text, _data.rotation_img_text, 0);
                    break;
                case 1:
                    SetData_Video(_root_res_id, _data.file);
                    break;
                case 2:
                    SetData_Flash(_root_res_id, _data.file);
                    break;
                case 3:
                case 4:
                case 5:
                case 6:
                    SetData_Office(_data.file);
                    break;
                case 7:
                    SetData_Image(_root_res_id, _data.file, 0);
                    break;
                case 9:
                    SetData_Html(_data.file);
                    break;
            }
        }
        /// <summary>
        /// 设置媒体数据
        /// </summary>
        /// <param name="_data"></param>
        public void SetData(resCourseListChildModel _data, Action<bool> _callback_fullscreen = null)
        {
            _fullscreen_callback = _callback_fullscreen;

            Reset();
            if (_data == null)
            {
                return;
            }

            _media_type = GetType(_data.file);
            if (_media_type < 0) return;

            string _root_res_id = BuildRoot(_data.id);
            switch (_media_type)
            {
                case 0:
                    SetData_Radio(_root_res_id, _data.file, _data.lyric_text, _data.rotation_img_text, _data.rotation_times);
                    break;
                case 1:
                    SetData_Video(_root_res_id, _data.file);
                    break;
                case 2:
                    SetData_Flash(_root_res_id, _data.file);
                    break;
                case 3:
                case 4:
                case 5:
                case 6:
                    SetData_Office(_data.file);
                    break;
                case 7:
                    SetData_Image(_root_res_id, _data.file, _data.rotation_times);
                    break;
                case 9:
                    SetData_Html(_data.file);
                    break;
            }
        }
        /// <summary>
        /// 设置媒体数据
        /// </summary>
        /// <param name="_data"></param>
        /// <param name="_callback_fullscreen"></param>
        public void SetData(resKindItemModel _data, Action<bool> _callback_fullscreen = null)
        {
            _fullscreen_callback = _callback_fullscreen;

            Reset();
            if (_data == null)
            {
                return;
            }

            _media_type = GetType(_data.file);
            if (_media_type < 0) return;

            string _root_res_id = BuildRoot(_data.id);
            switch (_media_type)
            {
                case 0:
                    SetData_Radio(_root_res_id, _data.file, _data.lyric_text, _data.rotation_img_text, _data.rotation_times);
                    break;
                case 1:
                    SetData_Video(_root_res_id, _data.file);
                    break;
                case 2:
                    SetData_Flash(_root_res_id, _data.file);
                    break;
                case 3:
                case 4:
                case 5:
                case 6:
                    SetData_Office(_data.file);
                    break;
                case 7:
                    SetData_Image(_root_res_id, _data.file, _data.rotation_times);
                    break;
                case 9:
                    SetData_Html(_data.file);
                    break;
            }
        }
       
        void SetData_Radio(string _root, string _path, string _lyric_text, string[] _rotation_img_text, int _rotation_times)
        {
            PART_MP3.Visibility = Visibility.Visible;
            PART_MP3.IsAutoPlay = IsAutoPlay;
            string _path_mp3 = Path.Combine(_root, Path.GetFileName(_path));
            PART_MP3.SetLyric(_lyric_text);
            if (_rotation_img_text == null || _rotation_img_text.Length == 0)
            {
                PART_MP3.SetImageList(null, 0);
            }
            else
            {
                var _tuples = new List<Tuple<string, string>>();
                foreach (string _img_url in _rotation_img_text)
                {
                    if (!_ex_img.Contains(Path.GetExtension(_img_url).ToLower().Substring(1)))
                        continue;

                    _tuples.Add(Tuple.Create(_img_url, Path.Combine(_root, Path.GetFileName(_img_url))));
                }
                if (_tuples.Count == 0)
                {
                    PART_MP3.SetImageList(null, 0);
                }
                else
                {
                    CheckDownload(_tuples.ToArray(), _success =>
                    {
                        PART_MP3.SetImageList(_tuples.Select(x => x.Item2).Where(x => File.Exists(x)).ToArray(), Convert.ToInt32(_rotation_times) / 1000);
                    }, false);
                }
            }
            if (File.Exists(_path_mp3))
            {
                PART_MP3.SetMP3(_path_mp3);
            }
            else
            {
                Download(_path, _path_mp3, _percentage =>
                {
                    PART_Dwonload_Progress.Maximum = 100;
                    PART_Dwonload_Progress.Value = _percentage;

                }, _success =>
                {
                    PART_Dwonload_Progress.Value = 0;
                    PART_Dwonload_Progress.Maximum = 1;

                    PART_MP3.SetMP3(_path_mp3);
                });
            }
        }

        void SetData_Video(string _root, string _path)
        {
            PART_Video.Visibility = Visibility.Visible;
            PART_Video.IsAutoPlay = IsAutoPlay;
            string _path_mp4 = Path.Combine(_root, Path.GetFileName(_path));
            if (File.Exists(_path_mp4))
            {
                PART_Video.SetVideo(_path_mp4, _fullscreen_callback);
            }
            else
            {
                Download(_path, _path_mp4, _percentage =>
                {
                    PART_Dwonload_Progress.Maximum = 100;
                    PART_Dwonload_Progress.Value = _percentage;

                }, _success =>
                {
                    PART_Dwonload_Progress.Value = 0;
                    PART_Dwonload_Progress.Maximum = 1;
                    if (_success)
                        PART_Video.SetVideo(_path_mp4, _fullscreen_callback);
                    else
                        PART_Video.Reset();
                });
            }
        }

        void SetData_Flash(string _root, string _path)
        {
            int _flash_type = 0;
            PART_Flash.Visibility = Visibility.Visible;
            //PART_Flash.SetFlash(_flash_type, _data.file);
            string _path_flash = Path.Combine(_root, Path.GetFileName(_path));
            if (File.Exists(_path_flash))
            {
                PART_Flash.SetFlash(_flash_type, _path_flash);
            }
            else
            {
                Download(_path, _path_flash, _percentage =>
                {
                    PART_Dwonload_Progress.Maximum = 100;
                    PART_Dwonload_Progress.Value = _percentage;

                }, _success =>
                {
                    PART_Dwonload_Progress.Value = 0;
                    PART_Dwonload_Progress.Maximum = 1;

                    PART_Flash.SetFlash(_flash_type, _path_flash);
                });
            }
            //if (_data.resources_name == "Flash")
            //{
            //    string _path_flash = Path.Combine(_root_res_id, Path.GetFileName(_data.file));
            //    if (File.Exists(_path_flash))
            //    {
            //        PART_Flash.SetFlash(_flash_type, _path_flash);
            //    }
            //    else
            //    {
            //        Download(_data.file, _path_flash, _percentage =>
            //        {
            //            PART_Dwonload_Progress.Maximum = 100;
            //            PART_Dwonload_Progress.Value = _percentage;

            //        }, _success =>
            //        {
            //            PART_Dwonload_Progress.Value = 0;
            //            PART_Dwonload_Progress.Maximum = 1;

            //            PART_Flash.SetFlash(_flash_type, _path_flash);
            //        });
            //    }
            //}
            //else
            //{
            //    _flash_type = _data.resources_name == "swf压缩包" ? 1 : 2;
            //    PART_Flash.SetFlash(_flash_type, _data.file);
            //}
        }

        void SetData_Office(string _path)
        {
            //int _type_office = 0;
            //if (_data.resources_name == "WORD") _type_office = 1;
            //if (_data.resources_name == "PDF") _type_office = 2;
            //if (_data.resources_name == "PPT") _type_office = 3;
            PART_Office.Visibility = Visibility.Visible;
            PART_Office.SetUrl(_path);
            //PART_Office.SetUrl(_data.file, Path.Combine(_root_res_id, $"{_data.id}.html"));
            //string _path_office = Path.Combine(_root_res_id, Path.GetFileName(_data.file));
            //if (File.Exists(_path_office))
            //{
            //    PART_Office.SetFile(_path_office, _type_office);
            //}
            //else
            //{
            //    Download(_data.file, _path_office, _percentage =>
            //    {
            //        PART_Dwonload_Progress.Maximum = 100;
            //        PART_Dwonload_Progress.Value = _percentage;

            //    }, _success =>
            //    {
            //        PART_Dwonload_Progress.Value = 0;
            //        PART_Dwonload_Progress.Maximum = 1;

            //        PART_Office.SetFile(_path_office, _type_office);
            //    });
            //}
        }

        void SetData_Image(string _root, string _path, int rotation_times = 0)
        {
            if (_path.Contains(";"))
            {
                PART_Images.Visibility = Visibility.Visible;
                var _tuples = new List<Tuple<string, string>>();
                string[] _images = _path.Split(';');
                foreach (string _img_url in _images)
                {
                    _tuples.Add(Tuple.Create(_img_url, Path.Combine(_root, Path.GetFileName(_img_url))));
                }
                CheckDownload(_tuples.ToArray(), _success =>
                {
                    PART_Images.SetImageList(_tuples.Select(x => x.Item2).Where(x => File.Exists(x)).ToArray(), Convert.ToInt32(rotation_times) / 1000, this.PART_LayoutRoot.ActualWidth, this.PART_LayoutRoot.ActualHeight);
                });
            }
            else
            {
                PART_Photo.Visibility = Visibility.Visible;
                string _path_photo = Path.Combine(_root, Path.GetFileName(_path));
                if (File.Exists(_path_photo))
                {
                    PART_Photo.SetPhoto(_path_photo);
                }
                else
                {
                    Download(_path, _path_photo, _percentage =>
                    {
                        PART_Dwonload_Progress.Maximum = 100;
                        PART_Dwonload_Progress.Value = _percentage;

                    }, _success =>
                    {
                        PART_Dwonload_Progress.Value = 0;
                        PART_Dwonload_Progress.Maximum = 1;
                        if (_success)
                            PART_Photo.SetPhoto(_path_photo);
                        else
                            PART_Photo.Reset();
                    });
                }
            }
        }

        void SetData_Html(string _path)
        {
            PART_Html.Visibility = Visibility.Visible;
            PART_Html.SetUrl(_path);
        }

        int GetType(string _path)
        {
            if (!string.IsNullOrEmpty(_path))
            {
                string _ex = Path.GetExtension(_path);
                if (_ex.Length > 1) _ex = _ex.Substring(1).ToLower();
                if (!string.IsNullOrEmpty(_ex))
                {
                    if (_ex_mp3.Contains(_ex))
                        return 0;
                    if (_ex_video.Contains(_ex))
                        return 1;
                    if (_ex_flash.Contains(_ex))
                        return 2;
                    if (_ex_excel.Contains(_ex))
                        return 3;
                    if (_ex_word.Contains(_ex))
                        return 4;
                    if (_ex_pdf.Contains(_ex))
                        return 5;
                    if (_ex_ppt.Contains(_ex))
                        return 6;
                    if (_ex_img.Contains(_ex))
                        return 7;
                    if (_ex_txt.Contains(_ex))
                        return 8;
                    if (_ex_html.Contains(_ex))
                        return 9;
                }
            }
            return -1;
        }

        string BuildRoot(int _id)
        {
            _root_res = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Local");
            string _root_res_id = Path.Combine(_root_res, _id.ToString());
            if (!Directory.Exists(_root_res_id)) Directory.CreateDirectory(_root_res_id);
            return _root_res_id;
        }

        void CheckDownload(Tuple<string, string>[] _list, Action<bool> _callback, bool _is_background = true)
        {
            if (_list == null || _list.Length == 0)
                return;

            if (_is_background)
            {
                Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() =>
                {
                    PART_Dwonload_Progress.Value = 0;
                    PART_Dwonload_Progress.Maximum = _list.Length;
                }));
                new Thread(new ThreadStart(() =>
                {
                    int _count_downloaded = 0;
                    foreach (var _tuple in _list)
                    {
                        if (!File.Exists(_tuple.Item2))
                        {
                            using (var _client = new WebClient())
                            {
                                _client.Proxy = null;
                                try
                                {
                                    _client.DownloadFile(new Uri(_tuple.Item1, UriKind.RelativeOrAbsolute), _tuple.Item2);
                                }
                                catch (Exception ex)
                                {
                                    App.Log(ex);
                                }
                            }
                        }

                        if (File.Exists(_tuple.Item2))
                            _count_downloaded++;

                        Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() =>
                        {
                            PART_Dwonload_Progress.Value++;
                        }));
                    }
                    Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() =>
                    {
                        PART_Dwonload_Progress.Value = 0;
                        PART_Dwonload_Progress.Maximum = 1;
                        _callback(_count_downloaded == _list.Length);
                    }));
                }))
                { IsBackground = true }.Start();
            }
            else
            {
                int _count_downloaded = 0;
                foreach (var _tuple in _list)
                {
                    if (!File.Exists(_tuple.Item2))
                    {
                        using (var _client = new WebClient())
                        {
                            _client.Proxy = null;
                            try
                            {
                                _client.DownloadFile(new Uri(_tuple.Item1, UriKind.RelativeOrAbsolute), _tuple.Item2);
                            }
                            catch (Exception ex)
                            {
                                App.Log(ex);
                            }
                        }
                    }

                    if (File.Exists(_tuple.Item2))
                        _count_downloaded++;
                }
                _callback(_count_downloaded == _list.Length);
            }
        }

        void Download(string _url, string _path, Action<int> _progress_callback, Action<bool> _callback)
        {
            if (string.IsNullOrEmpty(_url) || string.IsNullOrEmpty(_path))
                return;

            new Thread(new ThreadStart(() =>
            {
                using (var _client = new WebClient())
                {
                    _client.Proxy = null;
                    try
                    {
                        _client.DownloadProgressChanged += (s, e) =>
                        {
                            Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() =>
                            {
                                _progress_callback(e.ProgressPercentage);
                            }));
                        };
                        _client.DownloadFileCompleted += (s, e) =>
                        {
                            Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() =>
                            {
                                if (e.Cancelled || e.Error != null)
                                {
                                    _callback(false);
                                }
                                else
                                {
                                    _callback(true);
                                }
                            }));
                        };
                        _client.DownloadFileAsync(new Uri(_url, UriKind.RelativeOrAbsolute), _path);
                    }
                    catch (Exception ex)
                    {
                        App.Log(ex);
                    }
                }
            }))
            { IsBackground = true }.Start();
        }

        public void Reset()
        {
            PART_MP3.Reset();
            PART_Video.Reset();
            PART_Flash.Reset();
            PART_Office.Reset();
            PART_Photo.Reset();
            PART_Html.Reset();
            PART_Images.Reset();
            PART_Dwonload_Progress.Value = 0;
            PART_Dwonload_Progress.Maximum = 1;
            PART_Html.Visibility = Visibility.Collapsed;
            PART_MP3.Visibility = Visibility.Collapsed;
            PART_Video.Visibility = Visibility.Collapsed;
            PART_Flash.Visibility = Visibility.Collapsed;
            PART_Office.Visibility = Visibility.Collapsed;
            PART_Photo.Visibility = Visibility.Collapsed;
            PART_Images.Visibility = Visibility.Collapsed;
        }

        string _root_res;
        int _media_type;
        Action<bool> _fullscreen_callback;
        string[] _ex_img = new string[]
        {
            "png", "jpg", "jpeg", "bmp", "gif"
        };
        string[] _ex_txt = new string[]
        {
            "txt"
        };
        string[] _ex_pdf = new string[]
        {
            "pdf"
        };
        string[] _ex_flash = new string[]
        {
            "swf"
        };
        string[] _ex_html = new string[]
        {
            "html"
        };
        string[] _ex_excel = new string[]
        {
            "xls", "xlsx"
        };
        string[] _ex_word = new string[]
        {
            "doc", "docx"
        };
        string[] _ex_ppt = new string[]
        {
            "ppt", "pptx"
        };
        string[] _ex_mp3 = new string[]
        {
            "aac", "ac3", "acm", "amr", "ape", "caf", "flac", "m4a", "mp3", "ra", "wav", "wma"
        };
        string[] _ex_video = new string[]
        {
            "3gp",
            "asf",
            "avi",
            "dat",
            "dv",
            "flv",
            "f4v",
            "gif",
            "m2t",
            "m3u8",
            "m4v",
            "mj2",
            "mjepg",
            "mkv",
            "mov",
            "mp4",
            "mpe",
            "mpg",
            "mpeg",
            "mts",
            "ogg",
            "qt",
            "rm",
            "rmab",
            "ts",
            "vob",
            "wmv",
            "webm",
        };

    }
}
